package datatype;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author DuJiabao
 * @create 2020-12-29 23:28
 */
public class ArrayStack<Item> {
    private Item[] stack = (Item[]) new Object[10];
    private int first = 0;

    @Test
    public void test() {
        ArrayStack<Integer> arrayStack = new ArrayStack<Integer>();
        arrayStack.push(10);
        System.out.println(arrayStack.pop());
        for (int i = 0; i < 10; i++) {
            arrayStack.push(i);
        }
        System.out.println(arrayStack.toString());
        for (int i = 0; i < 3; i++) {
            System.out.println(arrayStack.pop());
        }
        for (int i = 0; i < 10; i++) {
            arrayStack.push(i);
        }
        System.out.println(arrayStack.toString());
    }

    public ArrayStack() {
    }

    public void push(Item item) {
        if (stack.length <= first) {
            resize(2 * stack.length);
        }
        stack[first++] = item;
    }

    private void resize(int length) {
        Item[] new_bag = (Item[]) new Object[length];
        for (int i = 0; i < first; i++) {
            new_bag[i] = stack[i];
        }
        stack = new_bag;
    }

    public Item pop() {
        if (first <= 0) {
            return null;
        }
        return stack[--first];
    }

    public boolean isEmpty() {
        return first == 0;
    }

    public int size() {
        return first;
    }

    public String forEach() {
        StringBuilder result = new StringBuilder("[ ");
        for (int i = 0; i < first; i++) {
            result.append(stack[i]);
            result.append(" ");
        }
        return result + "]";
    }

    @Override
    public String toString() {
        return "ArrayStack{" +
                ", first=" + first +
                "stack=" + forEach() +
                '}';
    }
}
